//
//  JYCurrencyViewController.swift
//  JYCalculate
//
//  Created by 何治军 on 2018/10/27.
//  Copyright © 2018 何治军. All rights reserved.
//

import UIKit
import SVProgressHUD

class JYCurrencyViewController: JYBaseViewController,JYBaseKeyBoardDelegate,JYCurrencyTextViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = Localized("function-currency")
        getTheRate()
    }
    
    override func setUpUI(){
        firstTextView.selectTextLab = {[weak self] in
            self?.secondTextView.isSelectedText = false
            self?.selectedTextView = self?.firstTextView
        }
        firstTextView.delegate = self
        view.addSubview(firstTextView)
        
        secondTextView.selectTextLab = {[weak self] in
            self?.firstTextView.isSelectedText = false
            self?.selectedTextView = self?.secondTextView
        }
        secondTextView.delegate = self
        view.addSubview(secondTextView)

        view.addSubview(firstRateLab)
        view.addSubview(secondRateLab)
        
        keyBoard.delegate = self
        view.addSubview(keyBoard)
    }
    
    override func setDefaultInfo(){
        self.selectedTextView = self.firstTextView
        firstTextView.model = self.listData[75]
        secondTextView.model = self.listData[27]

    }
    
    override func setTheLayout(){
        firstTextView.mas_updateConstraints { (make) in
            make?.top.mas_equalTo()(self.view)
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
        }
        secondTextView.mas_updateConstraints { (make) in
            make?.top.mas_equalTo()(self.firstTextView.mas_bottom)
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(self.firstTextView)
        }
        firstRateLab.mas_updateConstraints { (make) in
            make?.top.mas_equalTo()(self.secondTextView.mas_bottom)
            make?.left.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(self.firstTextView)?.multipliedBy()(0.6)
        }
        secondRateLab.mas_updateConstraints { (make) in
            make?.top.mas_equalTo()(self.firstRateLab)
            make?.left.mas_equalTo()(self.firstRateLab.mas_right)
            make?.right.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(self.firstRateLab)
            make?.width.mas_equalTo()(self.firstRateLab)
        }
        keyBoard.mas_updateConstraints { (make) in
            make?.top.mas_equalTo()(self.firstRateLab.mas_bottom)
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.bottom.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(self.view)?.multipliedBy()(0.6)
        }
    }
    
    //MARK: - JYBaseKeyBoardDelegate
    func clickKeyBoardBtn(item: String) {
        var newStr = self.selectedTextView.textLab.text! as NSString
        if "<-"==item {
            newStr = newStr.substring(to: newStr.length - 1) as NSString
            if newStr == "" {
                newStr = "0"
            }
        }else if "AC"==item {
            newStr = "0"
        }else if "."==item {
            if !newStr.contains(".") {
                newStr = self.selectedTextView.textLab.text!.appending(item) as NSString
            }
        }else{
            if newStr.length <= 12 {
                if newStr=="0" {
                    newStr = item as NSString
                }else{
                    newStr = self.selectedTextView.textLab.text!.appending(item) as NSString
                }
            }
        }
        self.selectedTextView.textLab.text = newStr as String
        self.cauclateTheMoney()
    }
    
    //MARK: - JYCurrencyTextViewDelegate
    func clickRightBtn(_ view: JYCurrencyTextView) {
        let vc = JYCurrencyListViewController()
        vc.dataArray = self.listData
        vc.selectedModelBlock = {[weak view,weak self](model) in
            let strongSelf = self
            view?.model = model
            strongSelf?.getTheRate()
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    /// 获取到汇率
    func getTheRate(){
        if self.firstTextView.model.code == "" || self.secondTextView.model.code == "" {
            return
        }
        if self.firstTextView.model.code == self.secondTextView.model.code {
            self.rate = "1"
            self.otherRate = "1"
            return
        }
        return
        let url = "http://op.juhe.cn/onebox/exchange/currency?key=\(CaculateAppKey)&from=\(self.firstTextView.model.code)&to=\(self.secondTextView.model.code)"
        SVProgressHUD.show()
        JYNetWorkManager.sharedInstance.getTheUrl(url: url, parameters: nil) { [weak self](reason, respondObj) in
            SVProgressHUD.dismiss()
            let strongself = self
            if respondObj != nil {
                let array = respondObj as! [[String:Any]]
                strongself?.rate = array[0]["exchange"] as! String
                strongself?.otherRate = array[1]["exchange"] as! String
                strongself?.refreshBottomView()
                strongself?.cauclateTheMoney()
            }else{
                SVProgressHUD.showError(withStatus: reason)
            }
        }
    }
    
    
    func refreshBottomView() {
        self.firstRateLab.text = "\(self.firstTextView.model.code) 1 = \(self.rate) \(self.secondTextView.model.code)"
        self.secondRateLab.text = "\(self.secondTextView.model.code) 1 = \(self.otherRate) \(self.firstTextView.model.code)"
    }
    
    func cauclateTheMoney() {
        let caculateStr = self.selectedTextView.textLab.text!
        if (self.selectedTextView == self.firstTextView) {
            if (self.rate != "") {
                self.secondTextView.textLab.text =  NTSWithDigit(MultiplicationM(caculateStr, b: self.rate),digit: 2);
            }
        }else{
            if (self.otherRate != "") {
                self.firstTextView.textLab.text =  NTSWithDigit(MultiplicationM(caculateStr, b: self.otherRate),digit: 2);
            }
        }
    }
    ///计算汇率
    var rate:String = ""
    var otherRate:String = ""
    
    //MARK - 属性组件
    private var selectedTextView:JYCurrencyTextView! = JYCurrencyTextView() {
        didSet{
            self.selectedTextView.isSelectedText = true
        }
    }

    private lazy var firstTextView:JYCurrencyTextView = {
        let v = JYCurrencyTextView()
        return v
    }()
    
    private lazy var secondTextView:JYCurrencyTextView = {
        let v = JYCurrencyTextView()
        return v
    }()
    
    private lazy var  firstRateLab:UILabel = {
        let lab = UILabel()
        lab.text = "? ? ?"
        lab.textColor = JYDetailGrayColor
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        return lab
    }()
    
    private lazy var  secondRateLab:UILabel = {
        let lab = UILabel()
        lab.text = "? ? ?"
        lab.textColor = JYDetailGrayColor
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        return lab
    }()
    
    private lazy var keyBoard:JYKeyBoardTypeOne = {
        let v = JYKeyBoardTypeOne()
        return v
    }()
    
    
    /// 汇率列表数据
    private var _array:[JYCurrencyModel] = []
    private var listData:[JYCurrencyModel]{
        do{
            let path = Bundle.main.path(forResource: "currencyCode", ofType: "json")
            let data = try NSData.init(contentsOfFile: path!) as Data
            let json = try JSONSerialization.jsonObject(with: data, options: []) as!  [String : Any]
            _array = JYCurrencyModel.mj_objectArray(withKeyValuesArray: json["result"] as? [Any]) as! [JYCurrencyModel]
        }catch{
            print(error)
        }
        return _array
    }

}

@objc protocol JYCurrencyTextViewDelegate : NSObjectProtocol {
    @objc optional func clickRightBtn(_ view:JYCurrencyTextView)
}

class JYCurrencyTextView: JYBaseView {
    
    var isSelectedText:Bool = false {
        didSet{
            self.textLab.isHighlighted = isSelectedText
        }
    }
    
    var model:JYCurrencyModel = JYCurrencyModel(){
        didSet{
            self.imageView.image = UIImage(named: model.countryCode.lowercased())
            self.titleLab.text =  Localized(model.countryCode)
            self.rightBtn.setTitle(model.code, for: .normal)
        }
    }
    
    weak var delegate: JYCurrencyTextViewDelegate?
    
    /// 选择textLab后的回调
    var selectTextLab = {() -> (Void) in}

    /// 标题
    lazy var titleLab:UILabel  = {
        let lab = UILabel()
        lab.textColor = JYNavigationBarColor
        lab.textAlignment = .center
        return lab
    }()
    
    private var marginView = UIView()//用于对图片的位置进行定位
    
    /// 图片
    private lazy var imageView = UIImageView()
    
    /// 输入内容
    lazy var textLab:UILabel = {
        let lab = UILabel()
        lab.textAlignment = .right
        lab.font = UIFont.systemFont(ofSize: 30)
        lab.highlightedTextColor = JYDetailRedColor
        lab.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapTheTextLab)))
        lab.isUserInteractionEnabled = true
        lab.adjustsFontSizeToFitWidth = true
        return lab
    }()
    
    /// 右侧选择按钮
    private lazy var rightBtn:UIButton = {
        let btn = UIButton()
        btn.setTitleColor(JYNavigationBarColor, for: .normal)
        btn.addTarget(self, action: #selector(clickTheRightBtn), for: .touchUpInside)
        return btn
    }()
    
    override func setUpUI() {
        super.setUpUI()
        self.addSubview(titleLab)
        self.addSubview(marginView)
        self.addSubview(imageView)
        self.addSubview(textLab)
        self.addSubview(rightBtn)
        
        titleLab.text = ""
        imageView.backgroundColor = JYDetailRedColor
        textLab.text = "0"
        rightBtn.setTitle("", for: .normal)
    }
    
    override func setTheConstraints() {
        super.setTheConstraints()
        self.titleLab.mas_updateConstraints { (make) in
            make?.top.mas_equalTo()(self)
            make?.centerX.mas_equalTo()(self)
            make?.width.mas_equalTo()(self)?.multipliedBy()(0.8)
            make?.height.mas_equalTo()(self)?.multipliedBy()(0.4)
        }
        self.marginView.mas_updateConstraints { (make) in
            make?.top.mas_equalTo()(self.titleLab.mas_bottom)
            make?.left.mas_equalTo()(self)
            make?.width.mas_equalTo()(self)?.multipliedBy()(0.25)
            make?.height.mas_equalTo()(self)?.multipliedBy()(0.6)
        }
        self.imageView.mas_updateConstraints { (make) in
            make?.centerX.mas_equalTo()(self.marginView)
            make?.centerY.mas_equalTo()(self.marginView)
            make?.width.mas_equalTo()(50)
            make?.height.mas_equalTo()(31)
        }
        self.textLab.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.marginView.mas_right)
            make?.width.mas_equalTo()(self)?.multipliedBy()(0.5)
            make?.centerY.mas_equalTo()(self.marginView)
            make?.height.mas_equalTo()(self)?.multipliedBy()(0.6)
        }
        self.rightBtn.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.textLab.mas_right)
            make?.right.mas_equalTo()(self)
            make?.centerY.mas_equalTo()(self.marginView)
            make?.height.mas_equalTo()(self)?.multipliedBy()(0.6)
        }
    }
    
    @objc func clickTheRightBtn() {
        self.delegate?.clickRightBtn?(self)
    }
    
    @objc fileprivate func tapTheTextLab() {
        self.selectTextLab()
    }
}


class JYKeyBoardTypeOne: JYBaseKeyBoard {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.btnTitleArray = ["7","8","9","","4","5","6","","1","2","3","","","",".","","0","AC","<-"]
    }
    
    override func setTheConstraints() {
        for index in 0 ..< self.keyBoardBtnArray.count {
            let btn = self.keyBoardBtnArray[index]
            btn.mas_updateConstraints { (make) in
                if index == 0 {
                    make?.left.mas_equalTo()(self)
                    make?.top.mas_equalTo()(self)
                }else if index == self.keyBoardBtnArray.count - 3{
                    make?.left.mas_equalTo()(self)
                    make?.bottom.mas_equalTo()(self)
                    make?.width.mas_equalTo()(self.keyBoardBtnArray[0])?.multipliedBy()(2)
                    make?.height.mas_equalTo()(self.keyBoardBtnArray[0])
                }else if index == self.keyBoardBtnArray.count - 2{
                    make?.top.mas_equalTo()(self)
                    make?.right.mas_equalTo()(self)
                    make?.width.mas_equalTo()(self.keyBoardBtnArray[0])
                    make?.height.mas_equalTo()(self.keyBoardBtnArray[0])?.multipliedBy()(2)
                }else if index == self.keyBoardBtnArray.count - 1{
                    make?.right.mas_equalTo()(self)
                    make?.bottom.mas_equalTo()(self)
                    make?.width.mas_equalTo()(self.keyBoardBtnArray[0])
                    make?.height.mas_equalTo()(self.keyBoardBtnArray[0])?.multipliedBy()(2)
                }else{
                    if (index % 4 == 0) {
                        make?.left.mas_equalTo()(self);
                        make?.top.mas_equalTo()(self.keyBoardBtnArray[index - 1].mas_bottom);
                    }else{
                        make?.left.mas_equalTo()(self.keyBoardBtnArray[index - 1].mas_right);
                        make?.top.mas_equalTo()(self.keyBoardBtnArray[index - 1]);
                    }
                    if (index % 4 == 3) {
                        make?.right.mas_equalTo()(self);
                    }
                    
                    make?.width.equalTo()(self.keyBoardBtnArray[0]);
                    make?.height.equalTo()(self.keyBoardBtnArray[0]);
                    
                    if (index == self.keyBoardBtnArray.count - 4){
                        make?.bottom.mas_equalTo()(self);
                    }
                }
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
